/*
 * Copyright (c) 2006, 2022, webrx.cn All rights reserved.
 *
 */
package cn.webrx;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * <p>Project: javase2203 - T20
 * <p>Powered by webrx On 2022-08-10 14:30:07
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 17
 */
public class T20 {
    AtomicInteger count = new AtomicInteger(0);

    public static void main(String[] args) {
        var t = new T20();
        for (int i = 0; i < 10000; i++) {
            new Thread(t::m, "T" + i).start();
        }

        try {
            TimeUnit.SECONDS.sleep(2);
            System.out.println(t.count.get());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    void m() {
        for (int i = 0; i < 10000; i++) {
            synchronized (this) {
                if (count.get() < 100 && count.get() >= 0) { //如果未加锁,之间还会有其他线程插进来
                    count.incrementAndGet();
                }
            }
        }
    }
}
